import os;
import time
import utime
import machine
from machine import Pin
import network
import webserver_app
import esp8266_auto_plant_flower as plant
import ntptime
import uasyncio
from machine import RTC
#webserver 运行入口主文件

p13 = Pin(2, Pin.OUT)    # led指示灯
p_motor = Pin(16, Pin.OUT)    # create output pin on GPIO0
p_motor.off()
def  wifi_init():
	# do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    time.sleep(3);
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('ChinaUnicom-1D69', 'bcg12345')
		# wlan.connect('Imilab-Office', 'Imilab$88888') # 连接到指定ESSID网络
        while not wlan.isconnected():
            time.sleep(1);
        print('network config:', wlan.ifconfig());

def  led_blink_show_status(timeout):
	i = 0;
	while i < timeout:
		# print("hello world "+str(i));
		time.sleep_ms(250);
		if i % 2 == 0:
			p13.on()  # set pin to "on" (high) level
		else:
			p13.off() # set pin to "off" (low) level
		i = i + 1
	p13.on()
def  ntp_sync_rtc():
	print("sync rtc form ntp")
	# ntptime.host = 'time.windows.com'
	# ntptime.settime()
	# tm = ntptime.time()  # 获取网络时间（从 1970 年 1 月 1 日开始的秒数）
	# tm = tm+ 8*3600 #东8区
	tm = 1691449772
	year, month, day, hour, minute, second, _, _ = utime.localtime(tm)  # 转换为元组形式
	print("Network Time:", year, month, day, hour, minute, second)# 输出结果
	rtc = RTC()  # 初始化 RTC
	rtc.datetime((year, month, day, 0, hour, minute, second, 0))  # 同步 RTC 时间

def  test_rtc():
	
	rtc = RTC()  # 初始化 RTC
	year, month, day, weekday, hour, minute, second, subsecond = rtc.datetime()
	rtc_time = utime.mktime((year+30, month, day, hour, minute, second, 0, 0))#年份使用2000+
	rtc_time -= 8*3600
	print("rtc=", year, month, day, weekday, hour, minute, second, subsecond)
	print("1970 seconds=", rtc_time)
#此文件cp到设备上以后重命名为main.py,micropython 就可以开机运行
#文件先闪烁30次led,并开始初始化wifi连接,等wifi连接成功后再闪烁10次,然后启动webserver
if __name__ == '__main__':
	led_blink_show_status(5)
	wifi_init()
	# ntp_sync_rtc()
	# test_rtc()
	led_blink_show_status(5)
	webserver_app.start_web()
	machine.reset()#监听退出后就重启设备

